package com.quark.service.system;


import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quark.constant.DsConfTypeEnum;
import com.quark.constant.DsJdbcUrlEnum;
import com.quark.mapper.system.SysDatasourceConfMapper;
import com.quark.model.system.gen.SysDatasourceConf;
import com.quark.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 张高昌
 * @version 版本
 * @date 2022/01/15 18:38
 * @description: 数据源业务层
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysDatasourceConfService {

    private final StringEncryptor stringEncryptor;

    private final DataSourceCreator druidDataSourceCreator;

    private final SysDatasourceConfMapper sysDatasourceConfMapper;

    /**
     * 分页查询数据源
     *
     * @param page
     * @param sysDatasourceConf
     * @return
     * @author 张高昌
     * @date 2022/01/15 18:47
     */
    public IPage<SysDatasourceConf> getDatasourceConfPage(Page page, SysDatasourceConf sysDatasourceConf) {

        return sysDatasourceConfMapper.selectPage(page, Wrappers.query(sysDatasourceConf));
    }

    /**
     * 查询全部数据源
     *
     * @return
     * @author 张高昌
     * @date 2022/01/16 12:51
     */
    public List<SysDatasourceConf> getList() {

        return sysDatasourceConfMapper.selectList(Wrappers.lambdaQuery());
    }

    /**
     * 根据id获取数据
     *
     * @param id
     * @return
     * @author 张高昌
     * @date 2022/01/16 13:03
     */
    public SysDatasourceConf getDataSourceConfInfo(Integer id) {
        return sysDatasourceConfMapper.selectById(id);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     * @author 张高昌
     * @date 2022/01/16 13:06
     */
    public boolean removeById(Integer id) {

        return sysDatasourceConfMapper.deleteById(id) > 0;
    }

    /**
     * 新增
     *
     * @param sysDatasourceConf
     * @return
     * @author 张高昌
     * @date 2022/01/16 13:19
     */
    public boolean saveDsByEnc(SysDatasourceConf sysDatasourceConf) {
        // 校验配置合法性
        if (!checkDataSource(sysDatasourceConf)) {
            return Boolean.FALSE;
        }
        // 添加动态数据源
        addDynamicDataSource(sysDatasourceConf);

        // 更新数据库配置
        sysDatasourceConf.setPassword(stringEncryptor.encrypt(sysDatasourceConf.getPassword()));
        sysDatasourceConfMapper.insert(sysDatasourceConf);
        return true;
    }

    public void addDynamicDataSource(SysDatasourceConf conf) {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setPoolName(conf.getName());
        dataSourceProperty.setUrl(conf.getUrl());
        dataSourceProperty.setUsername(conf.getUsername());
        dataSourceProperty.setPassword(conf.getPassword());
        DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);

        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
    }

    /**
     * 校验数据源配置是否有效
     *
     * @param conf 数据源信息
     * @return 有效/无效
     */
    public Boolean checkDataSource(SysDatasourceConf conf) {
        String url;
        // JDBC 配置形式
        if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
            url = conf.getUrl();
        } else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
            // 主机形式 sql server 特殊处理
            DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
            url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getInstance(), conf.getPort(), conf.getDsName());
        } else {
            DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
            url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
        }

        conf.setUrl(url);

        try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
        } catch (SQLException e) {
            log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 修改
     *
     * @param sysDatasourceConf
     * @return
     * @author 张高昌
     * @date 2022/02/11 20:25
     */
    public boolean updateDsByEnc(SysDatasourceConf sysDatasourceConf) {
        if (!checkDataSource(sysDatasourceConf)) {
            return Boolean.FALSE;
        }
        // 先移除
        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        dynamicRoutingDataSource.removeDataSource(sysDatasourceConfMapper.selectById(sysDatasourceConf.getId()).getName());

        // 再添加
        addDynamicDataSource(sysDatasourceConf);
        // 更新数据库配置
        if (StrUtil.isNotBlank(sysDatasourceConf.getPassword())) {
            sysDatasourceConf.setPassword(stringEncryptor.encrypt(sysDatasourceConf.getPassword()));
        }

        sysDatasourceConfMapper.updateById(sysDatasourceConf);
        return Boolean.TRUE;
    }

}
